/**
 * 
 */
package cn.edu.jlu.grid.vjm;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Logger;

/**
 * @author whb
 *
 */
public class VJobPool {
	/* map between an Integer and a Vector<Poolelement>, which the integer
	 * act as a resource reservaion handler, and all available vjobs will
	 * be stored in Vector<PoolElement>
	 */
	private HashMap<Integer, Vector<PoolElement> > pool = null;
	private Logger logger = null;
	private static VJobPool inst = null;
	private int reservationHandler = 0;
	
	/* singleton design pattern */
	private VJobPool() {
		pool = new HashMap<Integer, Vector<PoolElement> >();
		logger = Logger.getLogger(VJobPool.class.getName());
	}
	public static void init() {
		if(inst == null) inst = new VJobPool();
	}
	public static VJobPool getInstance() {
		if(inst == null) init();
		return inst;
	}
	
	public int allocateNewReservationHandler() {
		pool.put(reservationHandler, new Vector<PoolElement>());
		return reservationHandler++;
	}
	/* return the index of the newly added Cluster, this index is also
	 * known as the requestID
	 */
	public int addReservationRequest(int reservationHandler, Cluster c) {
		Vector<PoolElement> vpe = pool.get(reservationHandler);
		vpe.add(new PoolElement(c, new Vector<VJob>()));
		return vpe.size() - 1;
	}
	
	public void addVJob(int reservationHandler, int requestId, VJob vjob) {
		Vector<PoolElement> vpe = pool.get(reservationHandler);
		PoolElement pe = vpe.get(requestId);
		pe.vjobs.add(vjob);
	}
	public void setVJobGKContact(int reservationHandler, int requestId, int vjobId, String gkContact) {
		Vector<PoolElement> vpe = pool.get(reservationHandler);
		PoolElement pe = vpe.get(requestId);
		Vector<VJob> vjobs = pe.vjobs;
		int i;
		for(i = 0; i < vjobs.size(); i++) {
			if(vjobs.get(i).getId() == vjobId) {
				vjobs.get(i).setGkContact(gkContact);
				break;
			}
		}
		if(i >= vjobs.size()) {
			logger.severe("Specified VJobId doesn't exist");
		}
	}
	public Vector<VJob> getAllAvailableVJobs(int reservationHandler) {
		Vector<PoolElement> vpe = pool.get(reservationHandler);
		Vector<VJob> result = new Vector<VJob>();
		for(int i = 0; i < vpe.size(); i++) {
			result.addAll(vpe.get(i).vjobs);
		}
		return result;
	}
	public void release() {
		Collection c = pool.values();
		Iterator it = c.iterator();
		while(it.hasNext()) {
			Vector<PoolElement> ve = (Vector<PoolElement>) it.next();
			for(int i = 0; i < ve.size(); i++) {
				ve.get(i).release();
			}
		}
	}
	private class PoolElement {
		private Cluster cluster;
		private Vector<VJob> vjobs;
		PoolElement(Cluster c, Vector<VJob> v) {
			cluster = c;
			vjobs = v;
		}
		public void release() {
			for(int i = 0; i < vjobs.size(); i++) {
				vjobs.get(i).release();						
			}
		}
	}
}
